package memorphic.slide
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	
	import mx.core.IFlexDisplayObject;
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;
	import mx.states.IOverride;


	[DefaultProperty("popupObject")]
	
	public class PopUp implements IOverride
	{
		
		
		public var popupObject:IFlexDisplayObject;
		
		public var popupClass:Class;
		
		public var modal:Boolean = false;
		
		public var parent:DisplayObject;
		
		public var recycle:Boolean = true;
	
	
		public var centered:Boolean = true;
		
	
		private var popupInstance:IFlexDisplayObject;
		
		
		
		
		public function PopUp()
		{
		}

		public function initialize():void
		{
		}
		
		public function apply(parent:UIComponent):void
		{
			var parentContainer:DisplayObject = this.parent ? this.parent : parent;
			if(popupObject){
				popupInstance = popupObject;
				PopUpManager.addPopUp(popupInstance, parentContainer, modal);
			}else if(popupClass){
				if(recycle && popupInstance){
					PopUpManager.addPopUp(popupInstance, parentContainer, modal);
				}else{
					popupInstance = PopUpManager.createPopUp(parentContainer, popupClass, modal);
				}
			}
			
			var slideParent:IStateView = (parent is IStateView) ? 
					IStateView(parent) : SlideView.findParentView(parent);
			var popupRootView:IStateView = (popupInstance is IStateView) ?
					IStateView(popupInstance) : SlideView.findChildView(popupInstance as DisplayObjectContainer);
		//	if(popupRootView is IModifiableSlideView){
				popupRootView.parentView = slideParent;
		//	}
			/// TODO: handle delayed instanciation
			
			if(centered){
				PopUpManager.centerPopUp(popupInstance);
			}
		}
		
		public function remove(parent:UIComponent):void
		{
			PopUpManager.removePopUp(popupInstance);
			if(!recycle){
				popupInstance = null;
			}
		}
		
	}
}